<template>
  <view style="height: 100vh;background-color:#F1F2F6;">
    <up-navbar title="发起群聊" placeholder @leftClick="close"></up-navbar>
    <view style="margin: 20rpx; ">
      <scroll-view scroll-y :style="listHeightStyle" class="CreateGroupView">
        <up-form labelPosition="top" labelWidth="auto" :model="form" :rules="rules" ref="formRef">
          <up-form-item label="群名称:" prop="groupName">
            <up-input v-model="form.groupName" border="surround" placeholder="请输入群名称"></up-input>
          </up-form-item>
          <up-form-item label="群类型:" prop="groupTypeName">
            <view @click="pickerShow = true" style="width: 100%;">
              <up-input v-model="form.groupTypeName" border="surround" placeholder="请选择群类型" readonly
                :customStyle="{ pointerEvents: 'none' }"></up-input>
            </view>
          </up-form-item>
          <up-form-item label="项目名称:" prop="projectName">
            <up-input v-model="form.projectName" border="surround" placeholder="请输入项目名称"></up-input>
          </up-form-item>
          <up-form-item label="自动保存群文件到网盘:" prop="autoSave">
            <up-switch v-model="form.autoSave"></up-switch>
          </up-form-item>
          <up-form-item :label="`群成员: ${selections.length + 1}/1000`">
            <view class="member">
              <!-- 发起人固定 -->
              <view class="member-item">
                <up-image :src="userInfo.img_url" width="100%" height="100%" radius="10rpx">
                  <template #error>
                    <text>{{ showUserName(userInfo.username) }}</text>
                  </template>
                </up-image>
              </view>
              <!-- 成员列表 -->
              <view class="member-item" v-for="(item, index) in limitedMembers" :key="index">
                <view style="width: 100%; height: 100%;" v-if="index < 10" @click="selectMember">
                  <up-image :src="setUserImg(item)" width="100%" height="100%" radius="10rpx">
                    <template #error>
                      <text>{{ showUserName(item.username) }}</text>
                    </template>
                  </up-image>
                </view>
              </view>

              <view v-if="selections.length > 9" @click="selectMember" class="member-item more">
                <text>更多</text>
              </view>
              <!-- 添加 -->
              <view class="member-add" @click="selectMember">
                <up-icon color="#ccc" :size="20" name="plus"></up-icon>
              </view>

            </view>
          </up-form-item>
          <up-form-item label="群描述:" prop="des">
            <up-textarea v-model="form.des" placeholder="请输入内容"></up-textarea>
          </up-form-item>
        </up-form>
      </scroll-view>
    </view>

    <view style="position: fixed; bottom: 34rpx; width: 80%; left: 50%; transform: translateX(-50%);">
      <up-button type="primary" text="发起群聊" @click="submit"></up-button>
    </view>

    <u-modal :show="loading" :showConfirmButton='false'>
      <view class="slot-content">
        <rich-text nodes="正在发起群聊......"></rich-text>
      </view>
    </u-modal>

    <!-- 群类型 -->
    <up-picker :show="pickerShow" :columns="options" valueName="id" keyName="name" :closeOnClickOverlay="true"
      @cancel="pickerShow = false" @close="pickerShow = false" @confirm="confirm">
    </up-picker>

    <!-- 添加成员 -->
    <!--	 margin: 20rpx;	<member-picker ref="memberPicker" :userInfo="userInfo" @ok="addMember"></member-picker>-->
  </view>
</template>

<script>
import { chatApi } from '@/apis/cloud/chat';
import { objectToFormData } from "@/utils/chat";
import dayjs from 'dayjs';
import { getCurrentInstance } from "vue";
import MemberPicker from './MemberPicker.vue';
const AvaterBaseUrl = "https://cloud.mfarmers.com/dist/interface/public/upload/avatar/";
export default {
  components: {
    MemberPicker
  },
  props: {
    // userInfo: {
    // 	type: Object
    // },
    // uid: {
    // 	type: String
    // }
  },
  data () {
    return {
      loading: false,
      show: false,
      pickerShow: false,
      options: [
        [
          { id: 1, name: '商务项目' },
          //{id:2,name:'工程项目'},
          { id: 21, name: '工程合同' },
          { id: 22, name: '工程项目' },
          { id: 23, name: '工程施工' },
          { id: 24, name: '工程竣工' },
          { id: 3, name: '科研项目' },
          { id: 4, name: '生产项目' },
          { id: 5, name: '通用' }
        ]
      ],
      selections: [],
      form: {
        groupName: '',
        groupType: '',
        groupTypeName: '',
        projectName: '',
        autoSave: false,
        des: '',
      },
      rules: {
        'groupName': {
          type: 'string',
          required: true,
          message: '请填写群名称',
          trigger: ['blur', 'change']
        },
        'groupTypeName': {
          type: 'string',
          required: true,
          message: '请选择群类型',
          trigger: ['blur', 'change']
        },
      },
      userInfo: {},
      uid: '',
      listHeight: 0, // 动态计算的高度
      listHeightStyle: {}, // 动态计算的样式
      topHeight: 0,
      eventChannel: null
    }
  },
  computed: {
    limitedMembers () {
      return this.selections.slice(0, 9)
    }
  },
  created () {
    uni.$off('CreateGroupMemberPicker');
    this.calculateListHeight()
    uni.showLoading({
      title: '加载中....'
    });

    const instance = getCurrentInstance().proxy;
    this.eventChannel = instance.getOpenerEventChannel();
    let that = this
    this.eventChannel.on('ChatList', async function (data) {
      let res = JSON?.parse(data)
      if (res) {
        that.userInfo = res.userInfo
        that.uid = res.uid
      }
    })
    uni.hideLoading();
    uni.$on('CreateGroupMemberPicker', (data) => {      
      // this.selections = JSON.parse(data);   
      // this.addMember(data)
      let parsedData = JSON.parse(data);

      let filteredData = [];
      parsedData.forEach(item => {
        const id = item.cloud_worker_id || item.id; // 取有值的那个
        if (id == that.userInfo.worker_id) {
          // // 提示用户有重复
          // uni.showToast({
          //   title: '已包含自己，无需重复添加',
          //   icon: 'none',
          //   duration: 2000
          // });
        } else {
          filteredData.push(item);
        }
      });

      this.selections = [...new Map(filteredData.map(i => [i.cloud_worker_id || i.id, i])).values()];
    })

    console.log('that.userInfo',that.userInfo);
    
  },
  onUnload () {
    this.eventChannel.off('ChatList');
  },
  methods: {
    calculateListHeight () {
      // #ifdef APP-PLUS
      this.listHeightStyle = {
        height: 'calc(100vh - 400rpx)'
      };
      // #endif

      // #ifdef H5
      this.listHeightStyle = {
        height: 'calc(100vh - 375rpx)'
      };
      // #endif
    },
    addMember (data) {
      this.selections = JSON.parse(data);
    },
    selectMember () {
      let that = this
      uni.navigateTo({
        url: `/pages/chat/list/MemberPicker?ShowHide=true`,
        success: function (res) {
          res.eventChannel.emit('groupchat', {
            imgheadList: JSON.stringify(that.selections),
            userInfo: JSON.stringify(that.userInfo),
            source: 'CreateGroup',
          })
        }
      })
      // this.$refs.memberPicker.open(JSON.stringify(this.selections));
    },
    open () {
      // this.show = true;
    },
    close () {
      uni.reLaunch({
        url: "/pages/chat/list/index"
      })
      // this.show = false;
    },
    async submit () {
      if (this.form.groupName === '') {
        uni.$u.toast('请填写群名称')
        return
      }
      if (this.form.groupType === '') {
        uni.$u.toast('请选择群类型')
        return
      }
      if (this.selections.length === 0) {
        uni.$u.toast('群成员不能只有自己')
        return
      }
      this.loading = true;

      const memberArr = this.selections.map(item => {
        return `${item.username}|${item.account || ''}|${item.id}`
      })

      const params = {
        data: {
          uid: this.uid,
          createAccount: this.userInfo.chat_account,
          username: this.userInfo.worker_name,
          groupName: this.form.groupName,
          groupType: this.form.groupType,
          des: this.form.des,
          autoSave: this.form.autoSave,
          projectName: this.form.projectName,
          memberArr: memberArr,
          token: this.userInfo.token,
          account: this.userInfo.chat_account,
        },
        url: 'index.php/users/Group/createGroup'
      }

      const msg = await chatApi(this.userInfo.token, objectToFormData(params))

      // console.log(msg)

      if (msg.code === 200) {

        const sendData = {
          data: {
            account: "000000",
            isGroup: 1,
            group_id: msg.data.id,
            group_name: msg.data.group_name,
            group_avatar_data: msg.data.group_avatar_data,
            content: `${this.userInfo.username} 邀请你入群`,
            send_time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
            addAccount: this.userInfo.account
          },
          groupId: msg.data.id,
          msgId: `${this.userInfo.account}_${new Date().getTime()}`,
          timestamp: new Date().getTime(),
          type: "addGroup",
          uids: this.selections.map(item => item.account)
        }

        this.loading = false;
        this.close()
        uni.$emit('CreateGroupsuccess', sendData);
      } else {
        this.loading = false;
        uni.$u.toast(msg.info);
      }

    },
    confirm (e) {
      this.form.groupType = e.value[0].id;
      this.form.groupTypeName = e.value[0].name;
      console.log(this.form.groupTypeName)
      this.pickerShow = false;
    },
    // 名称超长处理
    showUserName (username) {
      if (username && username.length > 2) {
        return username.substr(1, 2);
      } else {
        return username;
      }
    },
    setUserImg (item) {
      if (item.avatar) {
        return item.avatar
      } else {
        const phone = item.friend_phone || item.phone || item.avatar;
        return AvaterBaseUrl + item.phone + '.jpg'
      }
    },
  }
}

</script>

<style scoped lang="scss">
.CreateGroupView {
  overflow-y: auto;
  //width:95vw;
  overflow-y: auto;
  background-color: #fff;
  border-radius: 10rpx;
  padding: 32rpx;
  box-sizing: border-box;
}

.member {
  display: flex;
  flex-wrap: wrap;

  .member-item {
    margin-top: 6rpx;
    margin-right: 8rpx;
    width: 82rpx;
    height: 82rpx;

    text {
      display: inline-block;
      width: 100%;
      height: 100;
      border-radius: 10rpx;
      color: #fff;
      font-size: 26rpx;
      text-align: center;
      line-height: 82rpx;
      background-color: #3D85FC;
    }
  }

  .member-add {
    margin-right: 8rpx;
    width: 82rpx;
    height: 82rpx;
    border-radius: 10rpx;
    border: 1px solid #ccc;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .more text {
    display: inline-block;
    width: 100%;
    height: 100%;
    border-radius: 10rpx;
    font-size: 28rpx;
    text-align: center;
    line-height: 82rpx;
  }
}
</style>
